//
//  CZComposeVC.swift
//  微博
//
//  Created by 霸气的刘吉庆 on 16/4/25.
//  Copyright © 2016年 ios. All rights reserved.
//

import UIKit
import SVProgressHUD
class CZComposeVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //加载界面
        setupUI()
        
    }
    
    //显示控制器的时候,是textView成为第一响应者
    override func viewDidAppear(animated: Bool) {
        
        textView.becomeFirstResponder()
    }
    
    
    
    @objc private func didClickBackButton(){
        //点击了dismiss按钮
        //撤销第一响应者
        self.textView.resignFirstResponder()
//        self.dismissViewControllerAnimated(true) { () -> Void in
//            
//            //结束之后干嘛呢,不知道
//            
//        }
        
        self.dismissViewControllerAnimated(true, completion: nil)
        
        
    }
    
    @objc private  func keyBoardChangeFrame(noti: NSNotification){
    
//        print(noti.userInfo)
        let endFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
    
//    print(endFrame)
        
        //调整toolBar的位置
        composeToolBar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(endFrame.origin.y - SCREENH)
        }
    
        //执行约束动画
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            self.view.layoutIfNeeded()
            }, completion: nil)
    }
    
    //设置正文的textView
    private lazy var textView: CZTextView = {
        let textView = CZTextView()
        //设置他的属性
        textView.placeHolderText = "啦啦啦啦拉拉阿拉啦啦啦啦啦啦啦😊😊😊😊😊😊😊😊"
        textView.font = UIFont.systemFontOfSize(16)
        textView.delegate = self
        //设置他的属性
        textView.keyboardDismissMode = .OnDrag
        //开启垂直方向的弹簧效果
        textView.alwaysBounceVertical = true
        
       //设置textView的keyBoard
        //键盘需要我们进行判断
//
//        textView.inputView = self.inputKeyBoard
        
        return textView
    }()
    
    //定义一个方法用来切换键盘的
    private func switchKeyBoard(){
        
        //判断当前的键盘是什么键盘,如果是系统键盘,将要切换到表情键盘,否则切换到系统键盘
//        if textView.inputView == nil {
//            textView.inputView = inputKeyBoard
//        }else{
//            
//            textView.inputView = nil
//        }
        //上面的直接可以使用三木运算符计算
        textView.inputView = (textView.inputView == inputKeyBoard) ? nil : inputKeyBoard
        //告诉toolBar当前显示的是什么键盘,他会根据这个属性来切换对应按钮的状态
        //toolBar里面需要有一个属性
        composeToolBar.isSystemKeyBoard = textView.inputView == nil
        
        //需要及时的更新
        textView.reloadInputViews()
        //重新加载输入的视图
        if !textView.isFirstResponder() {
            
            textView.becomeFirstResponder()
        }
        
        
        
        
    }
    
    //监听keyBoard的变化,需要执行的方法
   
    
    //懒加载keyboard
    private lazy var inputKeyBoard: CZInputKeyBoard = {
        
        let inputView = CZInputKeyBoard()
        //给他一个frame用于测试不然他显示不出来
        inputView.frame.size = CGSize(width: SCREENW, height: 228)
        
       return inputView
    }()
    
    //懒加载中间的titleView
    private lazy var titleView: UILabel = {
        let label = UILabel()
        
        //设置label的属性
        label.numberOfLines = 0
        //指定字体的颜色
        label.textColor = UIColor.blackColor()
        label.font = UIFont.systemFontOfSize(14)
        //设置文字居中
        label.textAlignment = .Center
        //取出模型判断
        if let name = CZUserAccountViewModel.sharedViewModel.account?.name {
        //设置属性的文字
            let text = "发微博\n\(name)"
            //求出字符串所在的范围
            let range = (text as NSString).rangeOfString(name)
            //把name截取出来
        //设置属性的文本
            let attrText = NSMutableAttributedString(string: text)
            
            
            //添加属性,范围内的设置属性
            
            attrText.addAttributes([NSForegroundColorAttributeName:UIColor.lightGrayColor(),NSFontAttributeName:UIFont.systemFontOfSize(20),NSStrokeWidthAttributeName:2,NSStrokeColorAttributeName: UIColor.redColor()], range: range)
            
            label.attributedText = attrText
            
            
            
        }else{
            //代表的是没有名字
            label.text = "发微博"
            
            
        }
        //设置大小,让他进行自适应
        label.sizeToFit()
        
        
        
        
        return label
    }()
    //懒加载
    private lazy var composeToolBar: CZComposeToolBar = {
       
        let composeToolBar = CZComposeToolBar(frame: CGRectZero)
        //这里注意循环引用
        composeToolBar.buttonClickClosure = { [weak self](type) in
            //点击按钮触发的事件
//            print(type)
//             case Picture = 0, Mention, Trend, Emoticon, Add
            switch type {
            case .Picture:
                //调用呼出imagePicker的方法
                self?.showImagePicker()
                break
            case .Mention:
                break
            case .Trend:
                break
            case .Emoticon:
                self?.switchKeyBoard()
                break
            case .Add:
                break
            }
            
            
        }
        
        return composeToolBar
        
    }()
    
    //显示相册
    private func showImagePicker(){
        let imagePicker = UIImagePickerController()
//        imagePicker.sourceType = .PhotoLibrary
        
        //设置代理
        imagePicker.delegate = self
        
        //弹出对应的控制器
        presentViewController(imagePicker, animated: true, completion: nil)
        
        
        
        
        
    }
    //懒加载一个pictureView
    private lazy var pictureView: CZComposePictureView = {
       
        let view = CZComposePictureView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
//        view
        //设置选中里面的闭包的属性
        view.seletedPicViewCellClosure = {[weak self] in
            
            self?.showImagePicker()
            
        }
//        view.backgroundColor = UIColor.redColor()
        
        return view
    }()
    
    
 

//懒加载右侧的按钮
    private lazy var rightButton: UIButton = {
       let button = UIButton(textColor: UIColor.whiteColor(), fontSize: 14)
        button.setTitle("发送", forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        //设置字体的不同状态下的颜色
        button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        //添加单击事件
        button.addTarget(self, action: "sendMessage", forControlEvents: .TouchUpInside)
        
        //设置右侧按钮的大小
        
        button.frame.size = CGSize(width: 45, height: 28)
        
        
        return button
    }()
    
    //点击了发送消息的按钮,那么我们如何做呢
    @objc private func sendMessage(){
        
        //发送的时候进行判断,判断里面是否有图片,有图片代表的就是upLoad,没有图片代表的是update
        if pictureView.hidden{
            upDate()
        }else{
            upload()
        }
        
//        //发送微博的地址https://api.weibo.com/2/statuses/update.json
//        let urlString = "https://api.weibo.com/2/statuses/update.json"
////        access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
////        status	true	string	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
//        //参数的内容,注意属性的可选,需要及时的合并和强解
//        let params = ["access_token":CZUserAccountViewModel.sharedViewModel.accessToken ?? "",
//        "status":textView.text!]
//        
////        CZNewWorkTools.sharedTools.request(urlString: urlString, paramenters: params, finished: <#T##CZRequestCallBack##CZRequestCallBack##(responseObject: AnyObject?, error: NSError?) -> ()#>)
//        CZNewWorkTools.sharedTools.request(CZRequestMethod.Post, urlString: urlString, paramenters: params) { (responseObject, error) -> () in
//            
//            if error != nil {
//                //如果error不等于nil代表的是有错误
//                print("错误\(error)")
//                SVProgressHUD.showErrorWithStatus("发送失败")
//                return
//                
//                
//                
//            }
//            
//            SVProgressHUD.showSuccessWithStatus("发送成功")
//            
//            
//        }
        
    }
    
    //发送图片的微博
    //access_token	false	string	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
//    status	true	string	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
    private func upload(){
        //请求地址
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        //请求参数
        let params = ["access_token":CZUserAccountViewModel.sharedViewModel.accessToken ?? "",
        "status":textView.emoticonText!]
        
//        var data: NSData?
//        data.
        //发送请求
    
//        CZNewWorkTools.sharedTools.POST(urlString, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
//            
//            //上传的第一张文件
//            let data = UIImagePNGRepresentation(self.pictureView.imagesArray.first!)!
//            formData.appendPartWithFileData(data, name: "pic", fileName: "哈哈", mimeType: "application/octet-stream")
////            formaData.appendPartWithFileData(data, name: "pic", fileName: "哈哈",mimeType: "application/octet-stream")
//            
//            }, progress: nil, success: { (_, responseObject) -> Void in
//                //成功
//                SVProgressHUD.showSuccessWithStatus("发送成功")
//                
//            }) { (_, error) -> Void in
//                //失败
//                print(error)
//                SVProgressHUD.showErrorWithStatus("发送失败")
//        }
//        
        
        //注意强解包
        let data  = UIImagePNGRepresentation(self.pictureView.imagesArray.first!)!
        
        //这个是发送问价你的请求
        CZNewWorkTools.sharedTools.upload(urlString, paramenters: params, Datas: ["pic":data]) { (responseObject, error) -> () in
            if error != nil {
                
                print("错误\(error)")
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            
           SVProgressHUD.showSuccessWithStatus("发送成功")
            
            
        }
        
        
        
    }
    
    
    
    
    //发送文字的微博
    private func upDate(){
        
        //发送请求
        
        //请求地址
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        //参数
        let params = ["access_token":CZUserAccountViewModel.sharedViewModel.accessToken ?? "",
            "status":textView.emoticonText!]
        //发送请求
        CZNewWorkTools.sharedTools.request(CZRequestMethod.Post, urlString: urlString, paramenters: params) { (responseObject, error) -> () in
            
            if error != nil {
                //如果error不等于nil代表的是有错误
                print("错误\(error)")
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
                
                
                
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
            
            
        }
    }
   

}

extension CZComposeVC: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    //选中完成执行的方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //获取到图片,需要进行压缩,获取到了图片我们将它添加到我们的pictureView里面
//        pictureView.imagesArray.append(image)

        //将图片进行压缩
        let img = image.scaleToWidth(600)
        
        //注意,这里商品列表的图片一般是10~30KB
        //商品详情的图片一般是50~100KB ,一般程序是100~120MB 超过120MB就需要我们做内存管理了
        
        pictureView.addImage(img)
        //手动调用dismiss方法
        picker.dismissViewControllerAnimated(true, completion: nil)
        
        
        
    }
    
}

//设置界面的内容进行封装
extension CZComposeVC{
    
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "didClickBackButton")
        //设置右侧的按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        //开始默认是禁用状态
        //设置button没用,必须设置navigation的状态
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleView
        
        
        
        
    }
    private func setupUI(){
        //设置界面
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
        
        view.addSubview(textView)
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            
            make.top.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(44)
            
            //            make.edges.equalTo(self.view)
        }
        
        view.addSubview(composeToolBar)
        //设置约束
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        textView.addSubview(pictureView)
        //设置约束
        pictureView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(10)
            make.top.equalTo(100)
            //设置他的宽度和高度
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(pictureView.snp_width)
        }
        
        //添加keyboard的监听事件
     NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didClickEmoticonButton:", name: CZEmoticonButtonNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didClickDeleteButton:", name: CZDeleteButtonNotification, object: nil)
        
        
        
    }
    //点击表情按钮通知执行的方法
    @objc private func didClickEmoticonButton(noti: NSNotification){
        //点击表情按钮,将按钮的内容显示到textView里面去
        let emoticonModel = noti.userInfo!["emoticonModel"] as! CZEmoticonModel
        
        //判断是否是emoji表情,如果是emoji表情,直接将emoji字符串直接赋值上去就ok了
        if emoticonModel.type == "1" {
            
            textView.insertText((emoticonModel.code! as NSString).emoji())
        }else{
            //将表情图片附上去
            print("表情数据")
            
            textView.insert(emoticonModel)
            //以下代码,我们直接写了一个分类
            //将表情的数据直接赋值上去
            //1.将现有的文字生成一个NSMutableString,注意这后面的参数是attributed类型的
//            let originalAttrString = NSMutableAttributedString(attributedString: textView.attributedText)
//            //2.通过表情生成图片
//            let image = UIImage(named: "\(emoticonModel.folderName ?? "")/\(emoticonModel.png ?? "")", inBundle: CZEmoticonKeyBoardViewModel.sharedViewModel.emoticonBundle, compatibleWithTraitCollection: nil)
//            //3.通过图片生成一个附着文本
//            let attach = NSTextAttachment()
//            attach.image = image
//            //设置图片的大小,最好就是跟字体一样的大小
//            let attachmentHW = textView.font!.lineHeight
//            attach.bounds = CGRect(x: 0, y: -4, width: attachmentHW, height: attachmentHW)
//            //创建一个attributeString
//            let attributeString = NSAttributedString(attachment: attach)
//            //4.将上面的东西添加到NSMutableString里面去
//            originalAttrString.appendAttributedString(attributeString)
//            //设置字体的大小,一个是图片一个是文字不会被覆盖么
//            originalAttrString.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, originalAttrString.length))
//            //5.将上面处理好的文字赋值给textView.attributeString
//            textView.attributedText = originalAttrString
        }
            
        
    }
//接受到删除按钮点击的时候执行的方法
    @objc private func didClickDeleteButton(noti: NSNotification){
        //点击删除按钮,回删
        textView.deleteBackward()
    }

    
    
    
    
    
    
}

extension CZComposeVC: UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    
    
}
